#include <iostream>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <cstring>
std::string get_cmd_type(const int cmd_type){
    std::string cmdtype;
    switch (cmd_type) {
            case EVHTTP_REQ_GET: cmdtype = "GET"; break;
            case EVHTTP_REQ_POST: cmdtype = "POST"; break;
            case EVHTTP_REQ_HEAD: cmdtype = "HEAD"; break;
            case EVHTTP_REQ_PUT: cmdtype = "PUT"; break;
            case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break;
            case EVHTTP_REQ_OPTIONS: cmdtype = "OPTIONS"; break;
            case EVHTTP_REQ_TRACE: cmdtype = "TRACE"; break;
            case EVHTTP_REQ_CONNECT: cmdtype = "CONNECT"; break;
            case EVHTTP_REQ_PATCH: cmdtype = "PATCH"; break;
            default: cmdtype = "unknown"; break;
    }
    return cmdtype;
}
// HTTP请求回调函数
void http_request_handler(struct evhttp_request *req, void *ctx) {
    // 获取请求方法
    const int method = evhttp_request_get_command(req);
    std::cout << "Received " << get_cmd_type(method) << " request" << std::endl;

    // 创建一个响应缓冲区
    struct evbuffer *response_buffer = evbuffer_new();
    if (!response_buffer) {
        std::cerr << "Failed to create response buffer" << std::endl;
        evhttp_send_error(req, HTTP_SERVUNAVAIL, "Server error");
        return;
    }

    // 设置响应内容
    evbuffer_add_printf(response_buffer, "Hello, World!\n");

    // 发送响应
    evhttp_send_reply(req, HTTP_OK, "OK", response_buffer);

    // 释放缓冲区
    evbuffer_free(response_buffer);
}

int main() {
    // 初始化libevent
    struct event_base *base = event_base_new();
    if (!base) {
        std::cerr << "Failed to create event base" << std::endl;
        return 1;
    }

    // 创建HTTP服务器
    struct evhttp *http_server = evhttp_new(base);
    if (!http_server) {
        std::cerr << "Failed to create HTTP server" << std::endl;
        return 1;
    }

    // 绑定到本地地址和端口
    if (evhttp_bind_socket(http_server, "0.0.0.0", 8080) != 0) {
        std::cerr << "Failed to bind to port 8080" << std::endl;
        return 1;
    }

    // 设置请求处理回调函数
    evhttp_set_gencb(http_server, http_request_handler, nullptr);

    std::cout << "HTTP server started on port 8080" << std::endl;

    // 进入事件循环
    event_base_dispatch(base);

    // 清理资源
    evhttp_free(http_server);
    event_base_free(base);

    return 0;
}
